using System;
using System.Collections.Generic;
using System.Data.Linq;
using System.Text;
using System.Net;

using Yammer;

namespace Behemoth.Tests.YammerTest {

  /// <summary>
  /// Yammer.Net example
  /// </summary>
  /// <example>
  /// yam myfeed
  /// yam post -m "this is a sample post"
  /// yam post -m "this is a sample post with an attachment" -a "c:\myImage.gif"
  /// yam post -m "this is a sample post with multiple attachments" -a "c:\myImage.gif;c:\myText.txt"
  /// </example>
  public class Program {

    const string CONSUMER_KEY = "caXFOFfgDQaCOXvZamvIQ";
    const string CONSUMER_SECRET = "mDYHrAHoh3Y52huOJkVk0uVQIVq2jCvkydfPJXjxTg";
    const string RETRIEVE_MY_FEED = "yam myfeed";
    const string POST_MESSAGE = "yam post";
    static void Main(string[] args) {
      Yammer.Settings.Storage = Yammer.Settings.StorageType.File;
      Yammer.Settings settings = Yammer.Settings.CheckConfiguration();
      if (settings == null) {
        Yammer.Auth auth = GetRequestToken();
        GetAccessToken(auth);
      } else
        Menu(true, ConfigureClient(settings), null, null);
    }

    private static OAuth.OAuthKey ConfigureClient(Yammer.Settings settings) {
      OAuth.OAuthKey key = new OAuth.OAuthKey(CONSUMER_KEY, CONSUMER_SECRET, settings.OAuth.TokenKey, settings.OAuth.TokenSecret);
      WebProxy proxy = null;
      if (settings.Proxy.Enable) {
        proxy = new System.Net.WebProxy();
        proxy.Address = new Uri(settings.Proxy.Address + ":" + settings.Proxy.Port);
        proxy.Credentials = new NetworkCredential(settings.Proxy.Id, settings.Proxy.Password);
      }
      return key;
    }

    public static Yammer.Auth GetRequestToken() {
      Yammer.Auth auth = Yammer.Auth.GetRequestToken(null, CONSUMER_KEY, CONSUMER_SECRET);
      if (auth != null) {
        auth.Authorize(null);
        Console.WriteLine("We've opened up a browser so you can authenticate this application with Yammer.");
        Console.WriteLine("Once you've authenticated, press any key to continue.");
        Console.ReadLine();
      }
      return auth;
    }

    public static void GetAccessToken(Yammer.Auth auth) {
      if (auth != null)
        auth.GetAccessToken();

      if (auth.Success)
        Menu(true, auth.Key, null, null);

    }

    public static void Menu(bool welcome, OAuth.OAuthKey key, WebProxy proxy, Yammer.Session session) {
      if (session == null)
        session = new Yammer.Session(key, proxy);

      if (welcome) {
        Console.WriteLine("Welcome to my Yammer application!");
        welcome = false;
      }

      string input = Console.ReadLine();
      string option = ParseInput(input);

      switch (option) {
        case RETRIEVE_MY_FEED:
          ReadMessages(Yammer.ApiWrapper.GetFollowingMessages(session));
          break;
        case POST_MESSAGE:
          PostMessage(input, session);
          break;
      }

      Menu(welcome, key, proxy, session);

    }

    public static string ParseInput(string input) {
      if (input.ToLower().Contains(RETRIEVE_MY_FEED))
        return RETRIEVE_MY_FEED;

      if (input.ToLower().Contains(POST_MESSAGE))
        return POST_MESSAGE;

      return null;
    }

    public static void ReadMessages(List<Yammer.Message> messages) {
      Console.WriteLine();
      foreach (Yammer.Message msg in messages) {
        string body = msg.Body.Plain;
        string timeStamp = msg.CreatedAt;

        Yammer.User sender = null;
        Yammer.Guide guide = null;
        Yammer.Message repliedToMessage = null;
        Yammer.User repliedToUser = null;

        //if message sent from user store user information
        if (msg.SenderType.ToUpper() == Yammer.SenderType.USER.ToString())
          sender = msg.References.Users.Find(delegate(Yammer.User u) { return u.Id == msg.SenderId.ToString(); });

        //if message sent from guide store guid information
        if (msg.SenderType.ToUpper() == Yammer.SenderType.SYSTEM.ToString())
          guide = msg.References.Guide;

        //if message is a reply, store replied-to-message
        if (msg.RepliedToId != null && msg.RepliedToId != string.Empty)
          repliedToMessage = msg.References.Messages.Find(delegate(Yammer.Message m) { return m.Id == msg.RepliedToId; });

        //if reply-to-message exists, store replied-to-user
        if (repliedToMessage != null)
          repliedToUser = msg.References.Users.Find(delegate(Yammer.User u) { return int.Parse(u.Id) == repliedToMessage.SenderId; });

        StringBuilder sb = new StringBuilder();
        //Write sender name
        if (sender != null)
          sb.Append(sender.FullName);
        //Write guid name
        if (guide != null)
          sb.Append(guide.FullName);
        //Write replied-to-user name
        if (repliedToUser != null)
          sb.Append(" in-reply-to: " + repliedToUser.FullName);
        sb.AppendLine();

        //Write message body
        sb.AppendLine(body);

        //Write attachments
        if (msg.Attachments.Count > 0)
          foreach (Yammer.Attachment attachment in msg.Attachments)
            sb.AppendLine(attachment.Name);

        //Write timestamp
        sb.AppendLine(timeStamp);

        Console.WriteLine(sb.ToString());
      }
    }


    public static void PostMessage(string input, Yammer.Session session) {
      //parse message
      string pattern = "-m\\s\"+.+?\"";
      System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(pattern, System.Text.RegularExpressions.RegexOptions.Singleline);
      System.Text.RegularExpressions.Match message = regex.Match(input);
      string body = string.Empty;
      if (message != null)
        body = message.Value.Replace("-m", "").Trim().Replace("\"", "");

      //parse attachments
      pattern = "-a\\s\"+.+?\"";
      regex = new System.Text.RegularExpressions.Regex(pattern, System.Text.RegularExpressions.RegexOptions.Singleline);
      List<string> attachmentList = new List<string>();
      if (regex.IsMatch(input)) {
        message = regex.Match(input);
        attachmentList.AddRange(message.Value.Replace("-a", "").Trim().Replace("\"", "").Split(';'));
      }

      //post message
      Yammer.ApiWrapper.PostMessage(body, session, attachmentList);
    }
  }
}